<html>
<head>

<title>Groovy Goodness: Getting Groovy with DOM</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Getting Groovy with DOM</h3>

<div class="post">
<p>Reading XML is easy with Groovy's <code>XmlParser</code>, <code>XmlSlurper</code> classes. But sometimes we get an XML structure as DOM from another application or Java component. So we need more low-level access at the DOM level: we are in a world of nodes and elements. We can use the <code>DOMCategory</code> to make the low-level handling more Groovy.</p>
<pre class="brush:groovy">
import groovy.xml.*
import groovy.xml.dom.*

def xml = '''
&lt;users&gt;
    &lt;user active=&quot;true&quot;&gt;
        &lt;fullname&gt;mrhaki&lt;/fullname&gt;
    &lt;/user&gt;
    &lt;user active=&quot;false&quot;&gt;
        &lt;fullname&gt;Hubert A. Klein Ikkink&lt;/fullname&gt;
    &lt;/user&gt;
&lt;/users&gt;
'''
def xmlDom = DOMBuilder.newInstance().parseText(xml)  // Create DOM structure.

def root = xmlDom.documentElement
use (DOMCategory) {
    def users = root.user
    assert 2 == users.size()
    
    assert 'User with fullname mrhaki is active' == userInfo(users[0])
    assert 'User with fullname Hubert A. Klein Ikkink is not active' == userInfo(users[1])

    assert 'mrhaki' == users.findAll { it.'@active'.toBoolean() }[0].fullname.text()
}

def userInfo(user) {
    def active = user.'@active'.toBoolean()
    def fullname = user.fullname.text()
    &quot;User with fullname $fullname is ${active ? 'active' : 'not active'}&quot;
}
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>